import {
  asyncRoutes,
  constantRoutes
} from '@/router'
import {
  generateTree
} from '@/utils/common';
import http from '@/utils/http';


// initial state
let state = {
  routes: [],
  addRoutes: [],
  buttons: []
}

/**
 * Getters
 * @type {import('vuex/types').GetterTree<typeof state>}
 */
const getters = {
  getRoutes: state => {
    return state.routes
  },
  getButtons: state => {
    return state.buttons
  }
}
/**
 * Mutations
 *  @type {import('vuex/types').MutationTree<typeof state>}
 */
const mutations = {
  setRoutes(state, routes) {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  setButtons(state, button) {
    // iterator(button)
    log(button)
    state.buttons = button
  },
}
/**
 * Actions
 *  @type {import('vuex/types').ActionTree<typeof state>}
 */
const actions = {
  generateRoutes({
    commit
  }) {
    return new Promise(async (resolve, reject) => {
      const {
        arr,
        button
      } = await http.get('/sys/menu/lists')

      // const async = _.cloneDeep(asyncRoutes)
      const async = asyncRoutes()
      let accessedRoutes = generateTree(async, arr, "/")

      accessedRoutes.push({
        path: '*',
        redirect: '/404',
        hidden: true,
        hide: true
      })

      commit('setRoutes', accessedRoutes)
      commit('setButtons', button)
      resolve(accessedRoutes)
    }).catch(e => {
      reject('error: accessedRoutes')
    })
  },
  resetRouter({
    commit
  }, obj) {
    commit('setRoutes')
    commit('setButtons')
  },
}

export default {
  namespaced: true, // 为模块开启命名空间
  state,
  getters,
  mutations,
  actions
}
